package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackStatMapper;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.album.TrackStat;
import com.atguigu.tingshu.query.album.TrackInfoQuery;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.album.*;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class TrackInfoServiceImpl extends ServiceImpl<TrackInfoMapper, TrackInfo> implements TrackInfoService {

    @Autowired
    private TrackInfoMapper trackInfoMapper;
    @Autowired
    private TrackStatMapper trackStatMapper;
    @Autowired
    AlbumInfoMapper albumInfoMapper;

    @Autowired
    private VodService vodService;
    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public void saveTrackInfo(Long userId, TrackInfoVo trackInfoVo) {
        TrackInfo trackInfo = BeanUtil.copyProperties(trackInfoVo, TrackInfo.class);
        trackInfo.setUserId(userId);
        trackInfo.setSource("1");
        trackInfo.setStatus(SystemConstant.TRACK_STATUS_PASS);
        AlbumInfo albumInfo = albumInfoMapper.selectById(trackInfo.getAlbumId());//获取专辑信息包含id什么的
        if (albumInfo == null) {
            throw new RuntimeException("专辑不存在");
        }
        trackInfo.setOrderNum(albumInfo.getIncludeTrackCount() + 1);
        TrackMediaInfoVo trackMediaInfoVo = vodService.getTrackMediaInfo(trackInfoVo.getMediaFileId());

        if (trackMediaInfoVo != null) {
            trackInfo.setMediaDuration(BigDecimal.valueOf(trackMediaInfoVo.getDuration()));
            trackInfo.setMediaSize(trackMediaInfoVo.getSize());
            trackInfo.setMediaUrl(trackMediaInfoVo.getMediaUrl());
//设置声音来源
            trackInfo.setSource(SystemConstant.TRACK_SOURCE_USER);
            //设置状态
            trackInfo.setStatus(SystemConstant.TRACK_STATUS_PASS);
            trackInfoMapper.insert(trackInfo);//插入数据到track_info表中

        }
        albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount() + 1);
        albumInfoMapper.updateById(albumInfo);//更新专辑信息

        this.saveTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_PLAY, 0);
        this.saveTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_COLLECT, 0);
        this.saveTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_PRAISE, 0);
        this.saveTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_COMMENT, 0);


    }

    @Override
    public void saveTrackStat(Long id, String trackStatPlay, Integer l) {
        TrackStat trackStat = new TrackStat();
        trackStat.setTrackId(id);
        trackStat.setStatType(trackStatPlay);
        trackStat.setStatNum(l);
        trackStatMapper.insert(trackStat);
    }

    @Override
    public Page<TrackListVo> findUserTrackPage(Integer page, Integer limit, TrackInfoQuery trackInfoQuery) {
        Page<TrackListVo> trackListVoPage = new Page<>(page, limit);
        if (trackInfoQuery != null) {
            trackListVoPage = trackInfoMapper.findUserTrackPage(trackListVoPage, trackInfoQuery);
        }
        return trackListVoPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTrackInfo(Long trackId, TrackInfoVo trackInfoVo) {
        TrackInfo trackInfo1 = trackInfoMapper.selectById(trackId);
        String mediaFileIdBefore = trackInfo1.getMediaFileId();
        String mediaFileIdAfter = trackInfoVo.getMediaFileId();
        TrackInfo trackInfo = BeanUtil.copyProperties(trackInfoVo, TrackInfo.class);
        if (!mediaFileIdBefore.equals(mediaFileIdAfter)) {

            vodService.removeMediaFile(mediaFileIdBefore);


            TrackMediaInfoVo trackMediaInfoVo = vodService.getTrackMediaInfo(trackInfoVo.getMediaFileId());
            trackInfo.setId(trackId);

            trackInfo.setMediaDuration(BigDecimal.valueOf(trackMediaInfoVo.getDuration()));
            trackInfo.setMediaSize(trackMediaInfoVo.getSize());
            trackInfo.setMediaType(trackMediaInfoVo.getType());
            trackInfo.setMediaUrl(trackMediaInfoVo.getMediaUrl());
        }
        trackInfoMapper.updateById(trackInfo);


    }

    @Override
    public void removeById1(Long trackId) {
        TrackInfo trackInfo = trackInfoMapper.selectById(trackId);
        Integer orderNum = trackInfo.getOrderNum();
        trackInfoMapper.deleteById(trackId);
        trackInfoMapper.updateTrackNum(trackInfo.getAlbumId(), orderNum);
        //4.删除声音统计记录
        // 创建 UpdateWrapper 对象
        LambdaUpdateWrapper<TrackStat> updateWrapper = new LambdaUpdateWrapper<>();
        // 设置删除条件
        updateWrapper.eq(TrackStat::getTrackId, trackId);
        trackStatMapper.delete(updateWrapper);
        //5.更新专辑包含声音数量减一
        AlbumInfo albumInfo = albumInfoMapper.selectById(trackInfo.getAlbumId());
        albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount() - 1);
        albumInfoMapper.updateById(albumInfo);
        //删除远程平台媒体文件
        vodService.removeMediaFile(trackInfo.getMediaFileId());
    }

    /**
     * 获取音乐数据
     *
     * @param trackId 追踪id
     * @return 轨道启动器
     */
    @Override
    public TrackStatVo getTrackStatVo(Long trackId) {

        TrackStatVo trackStatVo = trackInfoMapper.getTrackStatVo(trackId);
        return trackStatVo;
    }

    @Autowired
    private AlbumFeignClient albumFeignClient;

    @Override
    public Page<AlbumTrackListVo> findAlbumTrackPage(Long albumId, Integer page, Integer limit, Long userId) {
        Page<AlbumTrackListVo> trackInfoPage = new Page<>(page, limit);
        trackInfoPage = trackInfoMapper.getAlbumTrackListVo(trackInfoPage, albumId);
        //获取专辑类型
        AlbumInfo data = albumFeignClient.getAlbumInfo(albumId).getData();
        String payType = data.getPayType();
        Assert.notNull(data, "专辑不存在", albumId);
        //未登录
        if (userId == null) {
            //判断专辑是否是vip免费或付费
            if (data.getPayType().equals(SystemConstant.ALBUM_PAY_TYPE_VIPFREE) || data.getPayType().equals(SystemConstant.ALBUM_PAY_TYPE_REQUIRE)) {
                trackInfoPage.getRecords().forEach(albumTrackListVo -> albumTrackListVo.setIsShowPaidMark(true));

                // 筛选出免费集数，将其标记为非付费
                trackInfoPage.getRecords().stream()
                        .filter(albumTrackListVo -> albumTrackListVo.getOrderNum() <= data.getTracksForFree())
                        .forEach(albumTrackListVo -> albumTrackListVo.setIsShowPaidMark(false));
                // 用处理后的列表替换原分页结果中的记录

            }

        } else {

            //是否是vip进行下一步查询
            Boolean isNeedcheckPaymentStatus = false;
            if (!isNeedcheckPaymentStatus) {
                UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(userId).getData();
                Assert.notNull(userInfoVo, "用户查询异常", userId);
                Integer isVip = userInfoVo.getIsVip();
                Date vipExpireTime = userInfoVo.getVipExpireTime();
                if (payType.equals(SystemConstant.ALBUM_PAY_TYPE_VIPFREE)) {
                    if (isVip.intValue() == 0) {// 普通用户
                        isNeedcheckPaymentStatus = true;
                    }
                    if (isVip.intValue() == 1 && new Date().after(vipExpireTime)) {//是否为vip过期
                        // 会员，但已到期
                        isNeedcheckPaymentStatus = true;
                    }
                }
                if (payType.equals(SystemConstant.ALBUM_PAY_TYPE_REQUIRE)) {
                    isNeedcheckPaymentStatus = true;
                }
                if (isNeedcheckPaymentStatus) {
                    //获取声音列表
                    List<AlbumTrackListVo> list1 = trackInfoPage.getRecords().stream().filter(albumTrackListVo -> {
                        return albumTrackListVo.getOrderNum() > data.getTracksForFree();
                    }).toList();
                    //获取待验证的声音ID列表
                    List<Long> list = list1.stream()
                            .map(albumTrackListVo -> {
                                return albumTrackListVo.getTrackId();
                            }).toList();
                    Map<Long, Integer> result = userFeignClient.getuserIsPaidTrack(userId, albumId, list).getData();
                    for (AlbumTrackListVo albumTrackListVo : list1) {
                        Integer i = result.get(albumTrackListVo.getTrackId());//校验结果
                        if (i == 0) {//结果为0说明未购买声音
                            albumTrackListVo.setIsShowPaidMark(true);
                        }
                    }
                }


            }


        }

        return trackInfoPage;
    }

    @Override
    public List<Map<String, Object>> findUserTrackPaidList(Long trackId, Long userId) {
        //确定当前要购买的专辑剩余声音列表
        TrackInfo trackInfo = trackInfoMapper.selectById(trackId);
        Long albumId = trackInfo.getAlbumId();
        Integer orderNum = trackInfo.getOrderNum();
        AlbumInfo albumInfo = albumInfoMapper.selectById(albumId);
        QueryWrapper<TrackInfo> gt = new QueryWrapper<TrackInfo>()
                .eq("album_id", albumId).ge("order_num", orderNum);
        //获取剩余声音列表
        List<TrackInfo> trackInfoList = trackInfoMapper.selectList(gt);
        if (trackInfoList.isEmpty()) {
            throw new GuiguException(400, "没有更多声音了");
        }
        List<Long> needcheckIdList = trackInfoList.stream().map(TrackInfo::getId).toList();
        //剩余未购买的声音列表
        List<Long> checckedIdList = null;
        checckedIdList = userFeignClient.getuserIsPaidTrackIdList(albumId, needcheckIdList).getData();
        if (checckedIdList != null) {

            List<Map<String, Object>> mapList = new ArrayList<>();
            HashMap<String, Object> map = new HashMap<>();
            map.put("name", "本集"); // 显示文本
            map.put("price", albumInfo.getPrice()); // 专辑声音对应的价格
            map.put("trackCount", 1); // 记录购买集数
            mapList.add(map);
            int size = checckedIdList.size();
            for (int i1 = 10; i1 < 50; i1 += 10) {
                if (size >= i1) {
                    HashMap<String, Object> mapDynamic10 = new HashMap<>();
                    mapDynamic10.put("name", "往后" + i1 + "集");
                    mapDynamic10.put("price", albumInfo.getPrice().multiply(new BigDecimal(i1)));
                    mapDynamic10.put("trackCount", i1);
                    mapList.add(mapDynamic10);
                } else {
                    HashMap<String, Object> mapDynamic = new HashMap<>();
                    mapDynamic.put("name", "往后" + size + "集");
                    mapDynamic.put("price", albumInfo.getPrice().multiply(new BigDecimal(size)));
                    mapDynamic.put("trackCount", size);
                    mapList.add(mapDynamic);
                    break;
                }


            }

            return mapList;

        } else {
            throw new GuiguException(400, "没有可购买的声音");
        }
    }


    @Override
    public List<TrackInfo> getavalibleTrackIfo(Integer count, Long trackId) {
        //确定当前要购买的专辑剩余声音列表
        TrackInfo trackInfo = trackInfoMapper.selectById(trackId);
        Long albumId = trackInfo.getAlbumId();
        Integer orderNum = trackInfo.getOrderNum();
        AlbumInfo albumInfo = albumInfoMapper.selectById(albumId);
        QueryWrapper<TrackInfo> gt = new QueryWrapper<TrackInfo>()
                .eq("album_id", albumId).ge("order_num", orderNum);
        //获取剩余声音列表
        List<TrackInfo> trackInfoList = trackInfoMapper.selectList(gt);
        if (trackInfoList.isEmpty()) {
            throw new GuiguException(400, "没有更多声音了");
        }
        List<Long> needcheckIdList = trackInfoList.stream().map(TrackInfo::getId).toList();
        //剩余未购买的声音列表
        List<Long> checckedIdList = null;
        checckedIdList = userFeignClient.getuserIsPaidTrackIdList(albumId, needcheckIdList).getData();

        List<TrackInfo> trackInfos = trackInfoMapper.selectBatchIds(checckedIdList).stream().limit(count).toList();

        return trackInfos;
    }
}

